﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="BusinessDevelopmentController.cs" company="DissingNellemann">
//   
// All rights reserved </copyright>
// <summary>
//   The business development controller.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace Website.Controllers
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web.Mvc;

    using Website.CRUDServices;
    using Website.Models;
    using Website.Models.Styling;
    using Website.Models.ViewModels;

    using User = Website.Models.Domain.User;

    /// <summary>
    ///     The business development controller.
    /// </summary>
    [Authorize(Roles = "User, Admin")]
    public class BusinessDevelopmentController : BaseController
    {
        #region Public Methods and Operators

        /// <summary>
        ///     The get header items.
        /// </summary>
        /// <returns>
        ///     The list of headeritems for a business development view.
        /// </returns>
        public static List<TableViewHeaderItem> GetHeaderItems()
        {
            var headerItems = new List<TableViewHeaderItem>();
            var item1 = new TableViewHeaderItem { Text = "Dato", SortableName = "TimeOfActivity", IsSortable = true, };
            var item2 = new TableViewHeaderItem { Text = "Aktivitet", SortableName = string.Empty, IsSortable = false };
            var item3 = new TableViewHeaderItem { Text = "Beskrivelse", SortableName = string.Empty, IsSortable = false };
            var item4 = new TableViewHeaderItem { Text = "Profiler", SortableName = string.Empty, IsSortable = false };
            var item5 = new TableViewHeaderItem { Text = "Projekt", SortableName = string.Empty, IsSortable = false };
            headerItems.Add(item1);
            headerItems.Add(item2);
            headerItems.Add(item3);
            headerItems.Add(item4);
            headerItems.Add(item5);

            return headerItems;
        }

        /// <summary>
        /// The index.
        /// </summary>
        /// <param name="skip">
        /// The skip.
        /// </param>
        /// <param name="take">
        /// The take.
        /// </param>
        /// <param name="ds">
        /// The i ds.
        /// </param>
        /// <param name="orderBy">
        /// The order by.
        /// </param>
        /// <param name="sortAscending">
        /// The sort ascending.
        /// </param>
        /// <returns>
        /// The <see cref="ActionResult"/>.
        /// </returns>
        public ActionResult Index(int? skip, int? take, List<Guid> ids, string orderBy, bool? sortAscending)
        {
            this.Session["CurrentSubMenuSelection"] = "BusinessDevelopment";
            this.ViewData["DiscussionTopics"] = PrimitiveTypes.GetTopics();
            this.ViewData["Profiles"] = PrimitiveTypes.GetProfiles();
            this.ViewData["Projects"] = PrimitiveTypes.GetProjects();

            ListView<Activity> view = null;

            List<TableViewHeaderItem> headerItems = GetHeaderItems();

            CRUDServiceProvider.WithCRUDService(
                client =>
                {
                    var query = new ActivityQuery();
                    query.Settings = new SearchSettings
                    {
                        SortAscending = sortAscending ?? false,
                        Skip = skip ?? 0,
                        Take = take ?? 20,
                        OrderBy = !string.IsNullOrEmpty(orderBy) ? orderBy : "TimeOfActivity"
                    };
                    query.HasBusinessDevelopment = true;

                    IResult iRes = client.Query(query);
                    if (iRes != null)
                    {
                        var res = (ActivityResult)iRes;
                        view = new ListView<Activity>(
                            res.List.ToList(),
                            query.Settings.Skip ?? 0,
                            query.Settings.Take ?? 100000,
                            res.TotalRowCount,
                            query.Settings.OrderBy,
                            query.Settings.SortAscending ?? true,
                            headerItems,
                            "Index");

                    }
                });


            return View(view);
        }

        /// <summary>
        ///     The new business development.
        /// </summary>
        /// <returns>
        ///     The <see cref="ActionResult" />.
        /// </returns>
        public ActionResult NewBusinessDevelopment()
        {
            this.ViewData["Projects"] = PrimitiveTypes.GetProjects();
            this.ViewData["DiscussionTopics"] = PrimitiveTypes.GetTopics();
            ProfilesView pv = ProfilesView.GetRelated();
            pv.SortAscending = true;
            pv.Skip = 0;
            pv.Take = 10000;
            pv.Profiles = ProfilesView.GetProfilesList("Name", null, pv);
            this.ViewData["Profiles"] = pv;
            return View();
        }

        /// <summary>
        /// The new business development.
        /// </summary>
        /// <param name="datepicker">
        /// The datepicker.
        /// </param>
        /// <param name="location">
        /// The location.
        /// </param>
        /// <param name="profilesSelect">
        /// The profiles select.
        /// </param>
        /// <param name="ownerProjects">
        /// The owner projects.
        /// </param>
        /// <param name="comments">
        /// The comments.
        /// </param>
        /// <param name="status">
        /// The status.
        /// </param>
        /// <param name="talksSelect">
        /// The talks select.
        /// </param>
        /// <param name="andet">
        /// The andet.
        /// </param>
        /// <returns>
        /// The <see cref="ActionResult"/>.
        /// </returns>
        [HttpPost]
        [ValidateInput(false)] 
        public ActionResult NewBusinessDevelopment(
            DateTime? datepicker,
            Guid location,
            List<Guid> profilesSelect,
            List<Guid> ownerProjects,
            string comments,
            string status,
            List<Guid> talksSelect,
            string Andet)
        {
            // finish off BDA part of the Activity
            var bda = new BusinessDevelopmentActivity
            {
                AdditionalComments = comments,
                ID = Guid.NewGuid(),
                TopicElaboration = Andet,
                Topics = (talksSelect ?? new List<Guid>()).ToArray()
            };

            // fill out the superclass
            if (datepicker != null)
            {
                var act = new Activity
                {
                    Attendees = (profilesSelect ?? new List<Guid>()).ToArray(),
                    BDA = bda,
                    OwnerProjects = (ownerProjects ?? new List<Guid>()).ToArray(),
                    Commentary = status,
                    ID = Guid.NewGuid(),
                    Location = location,
                    TimeOfActivity = datepicker.Value,
                    Creator = (this.Session["LoggedInUser"] as User).ID
                };

                // save it!
                CRUDServiceProvider.WithCRUDService(
                    client =>
                    {
                        var cmd = new CreateActivityCommand { Dto = act };

                        client.ExecuteCommand(cmd);
                    });
            }
            else
            {
                this.ViewData["Projects"] = PrimitiveTypes.GetProjects();
                this.ViewData["DiscussionTopics"] = PrimitiveTypes.GetTopics();
                ProfilesView pv = ProfilesView.GetRelated();
                pv.SortAscending = true;
                pv.Skip = 0;
                pv.Take = 10000;
                pv.Profiles = ProfilesView.GetProfilesList("Name", null, pv);
                this.ViewData["Profiles"] = pv;
                this.ViewData["ErrorMessage"] = new MvcHtmlString("Der skal vælges en dato for mødet.");
                return View();
            }

            return this.RedirectToAction("Index");
        }

        public ActionResult UpdateBusinessDevelopment(Guid id)
        {
            this.ViewData["CreateLocationActionName"] = "CreateLocationJson";
            this.ViewData["Regions"] = PrimitiveTypes.GetRegions();
            this.ViewData["Projects"] = PrimitiveTypes.GetProjects();
            this.ViewData["DiscussionTopics"] = PrimitiveTypes.GetTopics();
            ProfilesView pv = ProfilesView.GetRelated();
            pv.SortAscending = true;
            pv.Skip = 0;
            pv.Take = 10000;
            pv.Profiles = ProfilesView.GetProfilesList("Name", null, pv);
            this.ViewData["Profiles"] = pv;
            // load object for editing
            var dto = new Activity();
            CRUDServiceProvider.WithCRUDService(
                client =>
                {
                    var query = new ActivityQuery { Settings = new SearchSettings { IDEquals = id } };

                    var res = client.Query(query) as ActivityResult;
                    if (res != null)
                    {
                        if (res.List.Any())
                        {
                            dto = res.List[0];
                        }
                    }
                });

            // ensure we have some content
            if (dto != null)
            {
                return View(dto);
            }

            // something buggered up. Better send them back to the index.
            return this.RedirectToAction("Index");
        }

        [HttpPost]
        [ValidateInput(false)] 
        public ActionResult UpdateBusinessDevelopment(
            Guid ID,
            Guid ID2,
            DateTime? datepicker,
            Guid location,
            List<Guid> profilesSelect,
            List<Guid> ownerProjects,
            string comments,
            string status,
            List<Guid> talksSelect,
            string Andet)
        {
            // finish off BDA part of the Activity
            var bda = new BusinessDevelopmentActivity
            {
                AdditionalComments = comments,
                ID = ID2,
                TopicElaboration = Andet,
                Topics = (talksSelect ?? new List<Guid>()).ToArray()
            };

            // fill out the superclass
            if (datepicker != null)
            {
                var act = new Activity
                {
                    Attendees = (profilesSelect ?? new List<Guid>()).ToArray(),
                    BDA = bda,
                    OwnerProjects = (ownerProjects ?? new List<Guid>()).ToArray(),
                    Commentary = status,
                    ID = ID,
                    Location = location,
                    TimeOfActivity = datepicker.Value,
                    Creator = (this.Session["LoggedInUser"] as User).ID
                };

                // save it!
                CRUDServiceProvider.WithCRUDService(
                    client =>
                    {
                        var cmd = new UpdateActivityCommand { Dto = act };

                        client.ExecuteCommand(cmd);
                    });
            }

            return this.RedirectToAction("Index");
        }


        public ActionResult ViewBusinessDevelopment(Guid id)
        {
            this.Init("Events");
            this.Session["SubMenuItems"] = ActivityController.CreateSubMenu();
            this.Session["CurrentSubMenuSelection"] = "BusinessDevelopment";

            this.ViewData["CreateLocationActionName"] = "CreateLocationJson";
            this.ViewData["Regions"] = PrimitiveTypes.GetRegions();
            this.ViewData["Projects"] = PrimitiveTypes.GetProjects();
            this.ViewData["DiscussionTopics"] = PrimitiveTypes.GetTopics();
            ProfilesView pv = ProfilesView.GetRelated();
            pv.SortAscending = true;
            pv.Skip = 0;
            pv.Take = 10000;
            pv.Profiles = ProfilesView.GetProfilesList("Name", null, pv);
            this.ViewData["Profiles"] = pv;
            // load object for editing
            var dto = new Activity();
            CRUDServiceProvider.WithCRUDService(
                client =>
                {
                    var query = new ActivityQuery { Settings = new SearchSettings { IDEquals = id } };
                    var res = client.Query(query) as ActivityResult;
                    if (res != null)
                    {
                        if (res.List.Any())
                        {
                            dto = res.List[0];
                        }
                    }
                });

            // ensure we have some content
            if (dto != null)
            {
                return View(dto);
            }

            // something buggered up. Better send them back to the index.
            return this.RedirectToAction("Index");
        }

        public ActionResult DeleteBDA(Guid id)
        {
            CRUDServiceProvider.WithCRUDService(client =>
            {
                CRUDServices.DeleteActivityCommand cmd = new DeleteActivityCommand() { Dto = id };
                client.ExecuteCommand(cmd);
            });
            return RedirectToAction("Index");
        }

        #endregion
    }
}